import store from "@/store";
export const installDirectives = (Vue) => {
  //这个setNestedProperty函数的目的主要作用
  // 假设用户v-m-model="ruleForm.brandLogo"这种格式
  // 可以根据'ruleForm.brandLogo'字符串，最终实现对obj.ruleForm.brandLogo的赋值
  function setNestedProperty(obj, propertyPath, value) {
    const properties = propertyPath.split(".");
    const lastProperty = properties.pop();

    let currentObj = obj;
    for (const property of properties) {
      if (
        !currentObj.hasOwnProperty(property) ||
        typeof currentObj[property] !== "object"
      ) {
        currentObj[property] = {};
      }
      currentObj = currentObj[property];
    }

    currentObj[lastProperty] = value;
  }

  Vue.directive("m-model", {
    bind: function (el, binding, vnode) {
      console.log(binding, vnode);
      // 在绑定时进行初始化
      const value = binding.value;
      const context = vnode.context;
      const component = vnode.componentInstance;

      // 监听组件的update事件，更新v-model的值
      component.$on("update", (newValue) => {
        console.log("检测到了upate", newValue);
        setNestedProperty(context, binding.expression, newValue);
      });

      // 监听v-model的变化，更新组件的值
      context.$watch(value, (newValue) => {
        component.$emit("update", newValue);
      });
    },
  });

  // 按钮级别的权限控制指令
  Vue.directive("access", {
    bind(el, binding, vnode) {
      // console.log("权限控制指令", el, binding, vnode);
      let { roleName } = store.state.user.userInfo.roleData;
      // console.log(el.style.display);
      // var styles = window.getComputedStyle(el);
      // // 获取display属性
      // var display = el.currentStyle.display;
      // console.log(display);
      let disp = binding.value.includes(roleName) ? "inline-block" : "none";
      el.style.display = disp;
    },
  });
};
